package org.swim.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.swim.session.UserManagerRemote;

/**
 * Servlet implementation class AdminNominations
 */
public class AdminNominations extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminNominations() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		int user = Integer.parseInt(request.getParameter("user"));
		HttpSession session = request.getSession();
		String action = request.getParameter("action");
		System.out.println(action);
		String status = (String) session.getAttribute("status");
			if(status.equals("admin")) {
				InitialContext ic;
				try {
					ic = new InitialContext();
					UserManagerRemote userManager = (UserManagerRemote)ic.lookup("UserManagerRemote");
					switch (action) {
					case "promote":
						userManager.nominateAdmin(user);
						System.out.println("Nominating admin");
						break;
					case "revoke":
						userManager.revokeAdmin(user);
						System.out.println("Revoking admin");
						break;
					}
		        } catch (NamingException e) {
					e.printStackTrace();
				}				
			} else
			{
				PrintWriter out = response.getWriter();  
				response.setContentType("text/html");  
				out.println("<script type=\"text/javascript\">");  
				out.println("alert('Access Denied');");  
				out.println("</script>");
			}
		request.getRequestDispatcher("/Profile?id=" + user).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
